<?php
/**
 * V6
 *
 */
class data_invitation_renren extends data_invitation {
	public function __construct() {
		parent::__construct();
		$this->expire_days = 6;			// public code的过期时间，天数
	}
	/**
	 * 列出可以被邀请的微博好友
	 *
	 * @param int $uid
	 * @param int $circle_id
	 * @return array = array (
	 * 		array (
	 * 			id		=>  	// renren_id
	 * 			name	=> 		// 
	 * 		),
	 * 		...............
	 * )
	 */
	public function friend_for_invite ($uid, $circle_id) {
		$uid		= intval($uid);
		$circle_id	= intval($circle_id);
		
		if ($uid and $circle_id) {
			$data_user = new data_user();
			$user = $data_user->one($uid);
			$data_circle = new data_circle();
			// 获得user的renren id 和 circle的权限
			if ($user['renren_id'] and $data_circle->is_member($uid, $circle_id)) {
				// 获取user的人人好友的renren_id和nickname
				$data_renren = new data_renren();
				$renren_friends = $data_renren->friends_getfriends($user['renren_id']);		// 返回 array (array(id, name), ...)
				if (is_array($renren_friends)) {
					// 获取圈子member的人人id
					$member = $data_circle->list_member($uid, $circle_id, 1, 0);		// 返回 array (array(id, ..., renren_id, ...), ...)
					if (is_array($member)) {
						foreach ($member as $v) {
							if ($v['renren_id']) {
								$m[] = $v['renren_id'];
							}
						}
					}
					// 获取已经发送过邀请的accepter
					$member = $this->db->execute('
						select
							accepter_id
						from
							invitation_renren
						where
							inviter_id	= "'.$uid.'"		and
							circle_id	= "'.$circle_id.'"
					');
					if (is_array($member)) {
						foreach ($member as $v) {
							$m[] = $v['accepter_id'];
						}
						unset($member);
					}
					// 遍历renren friends，排除member
					if (is_array($m)) {
						foreach ($renren_friends as $v) {
							if (array_search($v['id'], $m) === false) {
								$renren_friends_m[] = $v;
							}
						}
						if (is_array($renren_friends_m)) {
							return $renren_friends_m;
						} else return false;
					} else return $renren_friends;
				} else return false;
			} else return false;
		} else return false;
	}
	/**
	 * 发送人人notifications
	 * 		发送成功后写入数据库
	 *
	 * @param int $uid
	 * @param int $circle_id
	 * @param String $accepter_id_str
	 * @return bool			// false:参数错误；-1：不能发更多的通知了； -2:字符串超长； -3:发送通知时出现错误
	 */
	public function send ($uid, $circle_id, $accepter_id_str) {
		$my_friends 		= $this->friend_for_invite($uid, $circle_id);		// 可以被邀请的renren用户，已经检查过权限了，为了核实参数id_str
		$accepter_id_array	= format_id_string($accepter_id_str, true);		// 返回array
		
		// 检查circle权限
		if (is_array($my_friends) and is_array($accepter_id_array)) {
			// 循环核实renren id并构造@
			$code = $this->make_code('renren', $uid, $circle_id);
			foreach ($my_friends as $v) {
				if (array_search($v['id'], $accepter_id_array) !== false) {
					$real_friends[] = $v;									// 核实并重构
				}
			}
			unset($my_friends);
			unset($accepter_id_array);
			if (is_array($real_friends)) {
				$data_renren 	= new data_renren();
				$size 			= sizeof($real_friends);
				$token 			= login::get_token_from_cookie('renren');		// 从cookietoken中获得当前用户的renren id
				$max 			= $data_renren->admin_getallocation();			// 检查发送notifications的限额
				$me_renren 		= $data_renren->users_getinfo($token['uid']);	// 获取在人人网上name（因为这个名字也许和本网站的nickname不一样）
				if ($max and $max['notifications_per_day']>0 and $size<=$max['notifications_per_day']) {		// 没有超过通知限额
					$data_circle = new data_circle();
					$circle = $data_circle->one($uid, $circle_id);		// 用来获得circle title和privacy
					$code = $this->make_code('renren', $uid, $circle_id);
					
					// 构造notification的ids，构造新鲜事儿的feed message
					$ids 		= '';
					$feed = array (
						'name'			=> '点击这里查看邀请详情',
						'description'	=> '(只对被邀请者有效)',
						'url'			=> 'http://uread.me/invitation.php?ureadmecode='.$code,
						'message'		=> '我创建了一个主题阅读圈'.(($circle['privacy'] == 'public') ? '《'.$circle['title'].'》' : '').'，邀请'.(($size>1) ? '你们' : '你').'加入：',
					);
					foreach ($real_friends as $v) {
						$ids 				.= $v['id'].',';
						$feed['message'] 	.= $v['name'].',';
					}
					$ids 				= substr($ids, 		0, -1);
					$feed['message'] 	= substr($feed['message'], 0, -1);
					
					// 检查发布新鲜事儿的message长度
					if (mb_strlen($feed['message']) <= 200) {
						// 发布新鲜事 return:post_id, -3:字符串超长；-2：发布错误；-1：没有token
						$send_feed = $data_renren->feed_publishfeed($feed['name'], $feed['description'], $feed['url'], $feed['message']);
						// 发布通知 return:true; -1:no token; -2:error_code; -3:result_false
						$notification_msg = $me_renren['name'].'创建了一个主题阅读圈《'.$circle['title'].'》，邀请您加入：<a href="http://uread.me/invitation.php?ureadmecode='.$code.'">http://uread.me/invitation.php?ureadmecode='.$code.'</a>';
						$send_notification = $data_renren->notifications_send($ids, $notification_msg);
						if ($send_feed or $send_notification) {		// 只要有一个发布成功即可
							// 写入数据库
							$this->add($uid, $circle_id, $ids, $code);
							return true;
						} else return -3;		// 发送通知时出现错误
					} else return -2;		// 字符串超长
				} else return -1;			// 不能发更多的通知了
			} else return false;
		} else return false;
	}
	private function add ($inviter_id, $circle_id, $accepter_ids, $code) {
		$accepter_id_array = format_id_string($accepter_ids, true);		// 返回数组
		if ($inviter_id and $circle_id and is_array($accepter_id_array) and $code) {
			$sql = '
				insert into 
					invitation_renren
				(inviter_id, circle_id, accepter_id, code, dt, is_accepted)
					values
			';
			$dt = date('Y-m-d H:i:s');
			foreach ($accepter_id_array as $aid) {
				$sql .= '("'.$inviter_id.'", "'.$circle_id.'", "'.$aid.'", "'.$code.'", "'.$dt.'", 0),';
			}
			$sql = substr($sql, 0, -1);
			return $this->db->execute($sql);
		} else return false;
	}
	/**
	 * 通过邀请码返回邀请者的id和圈子id
	 * 		可能会返回多条记录
	 *
	 * @param String $code
	 * @return Array
	 */
	public function decode ($code) {
		if ($this->is_code($code) == 'renren') {
			$execute = $this->db->execute('
				select
					*
				from
					invitation_renren
				where
					code 			= "'.$code.'"	and
					is_accepted		= 0
			');
			if (is_array($execute)) {
				// 检查权限
				$data_circle = new data_circle();
				if ($data_circle->is_member($execute[0]['inviter_id'], $execute[0]['circle_id'])) {
					return $execute;
				} else {
					// 邀请者已经不再是圈子成员了，删除记录
					$this->db->execute('
						delete from
							invitation_renren
						where
							code = "'.$code.'"
					');
					return false;
				}
			} else return false;
		} else return false;
	}
	public function accept ($decode, $renren_id, $uid) {
		$uid	= intval($uid);
		$inv 	= $this->is_renren_id_in_decode($renren_id, $decode);			// 返回decode中accepter_id==renren_id的记录
		
		if ($uid and $inv) {		
			// 发布Event：加入圈子、加为好友，发布notice
			$data_event = new data_event();
			$event_param = array (
				'user_id'		=> $uid,
				'inviter_id'	=> $inv['inviter_id'],
				'circle_id'		=> $inv['circle_id'],
			);
			$data_event->add('invitation_accept', $event_param, 'high');
			
			// 标记invitation记录为已经接受
			
			$this->update_is_accepted($inv['id'], 1);
			
			return $uid;

		} else return false;
	}
	private function is_renren_id_in_decode ($renren_id, $decode) {
		if (is_array($decode) and data_user::is_renren_id($renren_id)) {
			foreach ($decode as $v) {
				if ($v['accepter_id'] == $renren_id) {
					return $v;
				}
			}
			return false;
		} else return false;
	}
	
	private function update_is_accepted ($id, $is_accepted) {
		$id				= intval($id);
		$is_accepted	= intval($is_accepted);
		
		if ($id) {
			return $this->db->execute('
				update
					invitation_renren
				set
					is_accepted		= "'.$is_accepted.'"
				where
					id	= "'.$id.'"
			');
		} else return false;
	}
}
?>